package com.example.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;


public class WifiActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private static final String TAG = "hello";
    private WifiManager mWifiManager;
    private WifiInfo mWifiInfo;
    private List<ScanResult> mScanResultList = new ArrayList<>();
    private TextView mText_wifi;
    private Button mBtn_open;
    private Button mBtn_close;
    private List<String> mWiFiSSIDList = new ArrayList<>();
    private WiFiListAdapter mWiFiListAdapter;
    private ListView mList;
    private Button mBtn_search;
    private AlertDialog.Builder mAlertDialog;

    private static final int WIFICIPHER_NOPASS = 0;
    private static final int WIFICIPHER_WPA = 1;
    private static final int WIFICIPHER_WEP = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi);
        requestPower();
        requestPower2();
        initView();
        //  initWiFi();
    }

    private void initWiFi() {
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        mScanResultList = mWifiManager.getScanResults();
        if (mScanResultList != null) {
            for (ScanResult scanResult : mScanResultList) {
                if (!mWiFiSSIDList.contains(scanResult.SSID)) {
                    mWiFiSSIDList.add(scanResult.SSID);
                    mWiFiListAdapter.addWiFi(scanResult);
                    mWiFiListAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void initView() {
        mText_wifi = findViewById(R.id.text_wifi);
        mBtn_open = findViewById(R.id.btn_open);
        mBtn_close = findViewById(R.id.btn_close);
        mWiFiListAdapter = new WiFiListAdapter();
        mList = findViewById(R.id.list);
        mList.setAdapter(mWiFiListAdapter);
        mBtn_search = findViewById(R.id.btn_search);


        mList.setOnItemClickListener(this);
        mBtn_open.setOnClickListener(this);
        mBtn_close.setOnClickListener(this);
        mBtn_search.setOnClickListener(this);
    }

    public void requestPower() {
        //判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                //这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false
            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }
    }

    public void requestPower2() {
        //判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                //这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false
            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_open:
                if (mWifiManager != null && (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED)) {
                    mWifiManager.setWifiEnabled(true);
                }
                break;
            case R.id.btn_close:
                if (mWifiManager != null && (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED)) {
                    mWifiManager.setWifiEnabled(false);
                }
            case R.id.btn_search:
                mWiFiListAdapter = new WiFiListAdapter();
                mList.setAdapter(mWiFiListAdapter);
                mScanResultList.clear();
                mWiFiSSIDList.clear();
                initWiFi();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ScanResult result = mWiFiListAdapter.getWiFi(position);
        connectInit(result);
        String capa = result.capabilities;
        Log.i(TAG, "onItemClick: " + capa.toString());

    }

    private void connectInit(final ScanResult result) {
        WifiConfiguration configuration = new WifiConfiguration();
        final String capabilities = result.capabilities;
        int type = WIFICIPHER_WPA;
        if (!TextUtils.isEmpty(capabilities)) {
            if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                type = WIFICIPHER_WPA;
            } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                type = WIFICIPHER_WEP;
            } else {
                type = WIFICIPHER_NOPASS;
            }
            configuration = isExsits(result.SSID);
            if (configuration == null) {
                if (type != WIFICIPHER_NOPASS) {
                    final EditText editText = new EditText(this);
                    final int finaType = type;
                    mAlertDialog = new AlertDialog.Builder(this);
                    mAlertDialog.setTitle("请输入wifi密码:");
                    mAlertDialog.setView(editText);
                    mAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            WifiConfiguration config = new WifiConfiguration();
                            config = creatWiFiInfo(result.SSID, editText.getText().toString(), finaType);
                            wifiConnect(config);


                            Intent intent = new Intent(WifiActivity.this, MainActivity.class);
                            startActivity(intent);


                        }
                    });
                    mAlertDialog.setNegativeButton("CANCEL", null).show();
                } else {
                    configuration = creatWiFiInfo(result.SSID, "", type);
                    wifiConnect(configuration);
                }
            } else {
                wifiConnect(configuration);
            }
        }

    }

    private void wifiConnect(WifiConfiguration configuration) {
        final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int wcgId = wifiManager.addNetwork(configuration);
        wifiManager.enableNetwork(wcgId, true);

    }

    private WifiConfiguration creatWiFiInfo(String ssid, String password, int finaType) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";
        if (finaType == WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (finaType == WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    private WifiConfiguration isExsits(String ssid) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return null;
        }
        Log.i(TAG, "isExsits: 22222222222222");
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration wifiConfiguration : configuredNetworks) {
            if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
                return wifiConfiguration;
            }
        }
        return null;


    }


    public class WiFiListAdapter extends BaseAdapter {

        private LayoutInflater mInflater;
        private List<ScanResult> mWiFiList;

        public WiFiListAdapter() {
            mInflater = getLayoutInflater();
            mWiFiList = new ArrayList<ScanResult>();
        }

        public void addWiFi(ScanResult scanResult) {

            mWiFiList.add(scanResult);
        }

        public ScanResult getWiFi(int position) {
            return mWiFiList.get(position);
        }

        @Override
        public int getCount() {
            return mWiFiList.size();
        }

        @Override
        public Object getItem(int position) {
            return mWiFiList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.wifi_adapter, null);
            TextView text_WiFiName = convertView.findViewById(R.id.text_WiFiName);
            TextView text_WiFiAddress = convertView.findViewById(R.id.text_WiFiAddress);
            TextView text_WiFiRSSI = convertView.findViewById(R.id.text_WiFiRSSI);

            ScanResult scanResult = mWiFiList.get(position);
            text_WiFiName.setText(scanResult.SSID);
            text_WiFiAddress.setText(scanResult.BSSID);
            text_WiFiRSSI.setText(String.valueOf(scanResult.level));

            return convertView;
        }
    }
}
